import md5 from 'crypto-js/md5'

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string') {
      if (/^[0-9]+$/.test(time)) {
        time = parseInt(time)
      } else {
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach((v) => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}

/**
 * 处理树格式
 * import { arr2tree } from '@/utils'
 * const list  = arr2tree (arr,{id:'code',parentId:'parentCode',childrenKey:'children'})
 * @param {*} arr 数据
 * @param {*} config 配置
 */
export function arr2tree(arr = [], config = {}) {
  const { id = 'id', parentId = 'parentId', childrenKey = 'children' } = config

  const map = {}
  for (const iterator of arr) {
    map[iterator[id]] = iterator
  }
  for (const iterator of arr) {
    const key = iterator[parentId]
    if (!(key in map)) continue
    iterator.parent = map[key]
    map[key][childrenKey] = (map[key][childrenKey] || []).concat(iterator)
  }
  const newArr = []
  Object.keys(map).forEach((key) => {
    if (!(map[key][parentId] in map)) {
      newArr.push(map[key])
    }
  })
  return newArr
}

/**
 * 处理树格式转一维数组 import { tree2arr } from '@/utils'
 * @param {*} arr 数据
 * @param {*} config 配置
 */
export function tree2arr(arr = [], config = {}) {
  const list = []
  const { childrenKey = 'children' } = config

  const getChildData = (e) => {
    const childList = e[childrenKey] || []
    list.push(childList.length > 0 ? childList.map((m) => getChildData(m)) : e)
  }

  arr.forEach((e) => {
    const childList = e[childrenKey] || []
    list.push(childList.length > 0 ? childList.map((m) => getChildData(m)) : e)
  })
  return list
}

/**
 * 处理快讯列表目录数据
 * @param {*} arr 数据
 */
export function newsListarr(arr = []) {
  const list = {}
  arr.forEach((item) => {
    const { issueTm } = item
    if (issueTm) {
      const month =
        issueTm.substring(5, 6) === '0'
          ? issueTm.substring(6, 7)
          : issueTm.substring(5, 7)
      const date =
        issueTm.substring(8, 9) === '0'
          ? issueTm.substring(9, 10)
          : issueTm.substring(8, 10)
      item.modifyTm = `${issueTm.substring(0, 4)}年${month}月`
      item.issueTms = `${month}月${date}日`
    }
    if (list[item.modifyTm]) {
      list[item.modifyTm].push(item)
    } else {
      list[item.modifyTm] = [item]
    }
  })
  return Object.values(list)
}

/**
 * 获取上一个完整月
 * @param
 */
export function getlastMonth() {
  var date = new Date()
  var months = date.getMonth() + 1
  var m = '0' + (months - 1)
  var y = date.getFullYear()
  if (months === 1) {
    y--
    m = '12'
  }
  return `${y}-${m.substr(m.length - 2, 2)}`
}

// 省市转为树结构
export function cityArrToTree(arr) {
  arr.forEach((element) => {
    arr.forEach((element2) => {
      if (element.id === element2.parentId) {
        if (!element.children) {
          element.children = []
        }
        element.children.push(element2)
      }
    })
  })
  // console.log(arr)
  return arr.filter((item) => item.levels === '1')
}

// 深克隆
export function deepClone(obj) {
  // 1、判断是否为引用数据类型,递归结束条件
  if (typeof obj !== 'object' || obj == null) {
    return obj
  }
  // 2、初始化为数组或对象
  let result

  if (obj instanceof Array) {
    result = []
  } else {
    result = {}
  }

  // 3、循环递归复制对象属性，直到基础数据类型
  for (const key in obj) {
    // 防止原型链也被oldObj影响
    // eslint-disable-next-line no-prototype-builtins
    if (obj.hasOwnProperty(key)) {
      result[key] = deepClone(obj[key])
    }
  }
  return result
}

// MD5加密，不可逆
export function encryptByMd5(str) {
  // const salt = 'customs-platform-admin-web' // 加盐
  // return md5(str + salt).toString()
  return md5(str).toString()
}
